package com.xxx.mall.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxx.mall.mapper.CategoryBrandMapper;
import com.xxx.mall.model.CategoryBrand;
import com.xxx.mall.service.CategoryBrandService;
import com.xxx.mall.vo.CategoryVO;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 品牌分类关联信息 服务实现类
 * </p>
 *
 * @author 邢晨旭
 * @since 2023-11-15
 */
@Service
public class CategoryBrandServiceImpl extends ServiceImpl<CategoryBrandMapper, CategoryBrand> implements CategoryBrandService {

    @Override
    public void saveByCategoryIds(Long brandId, List<Long> categoryIds) {
        if (CollUtil.isEmpty(categoryIds)) {
            return;
        }
        List<CategoryBrand> categoryBrandList = new ArrayList<>();
        categoryIds.forEach(categoryId -> {
            CategoryBrand categoryBrand = new CategoryBrand();
            categoryBrand.setBrandId(brandId);
            categoryBrand.setCategoryId(categoryId);
            categoryBrandList.add(categoryBrand);
        });
        CategoryBrandService categoryBrandService = (CategoryBrandService) AopContext.currentProxy();
        categoryBrandService.saveBatch(categoryBrandList);
    }

    @Override
    public void updateByCategoryIds(Long brandId, List<Long> categoryIds) {
        if (CollUtil.isEmpty(categoryIds)) {
            return;
        }
        //数据库保存的老数据
        List<Long> categoryIdDb = getCategoryIdBrandId(brandId);
        List<Long> addList = new ArrayList<>();
        categoryIds.forEach(categoryId -> {
            if (!categoryIdDb.contains(categoryId)) {
                addList.add(categoryId);
            }
        });
        CategoryBrandService categoryBrandService = (CategoryBrandService) AopContext.currentProxy();
        if (CollUtil.isNotEmpty(addList)) {
            categoryBrandService.saveByCategoryIds(brandId, addList);
        }
        categoryIdDb.removeAll(categoryIds);
        if (CollUtil.isNotEmpty(categoryIdDb)) {
            baseMapper.deleteByBrandIdAndCategoryIds(brandId, categoryIdDb);
        }
    }

    @Override
    public List<CategoryVO> queryCategoryByBrandId(Long brandId) {
        return baseMapper.queryCategoryByBrandId(brandId);
    }

    @Override
    public void removeByBrandId(Long brandId) {
        baseMapper.deleteByBrandIdAndCategoryIds(brandId, null);
    }

    private List<Long> getCategoryIdBrandId(Long brandId) {
        return baseMapper.getCategoryIdBrandId(brandId);
    }
}
